package cn.topcodes.tcsf.codegen.ui;

import cn.topcodes.tcsf.codegen.domain.entity.Entity;
import cn.topcodes.tcsf.codegen.domain.entity.Field;
import cn.topcodes.tcsf.codegen.domain.entity.Program;
import cn.topcodes.tcsf.codegen.utils.ScreenUtil;
import cn.topcodes.tcsf.codegen.utils.SqliteOpenHelper;
import com.j256.ormlite.dao.ForeignCollection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Unicorn
 */
public class ProgramDialog extends javax.swing.JDialog {
    
    private DefaultListModel model = new DefaultListModel();

    public ProgramDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        ScreenUtil.initLocation(this);
        
        ImageIcon imageIcon = new ImageIcon("resource/images/logo.png");  
        this.setIconImage(imageIcon.getImage());  
        
        try {
            loadData();
        }catch(Exception e) {
            JOptionPane.showMessageDialog(this, "加载项目信息失败：" + e.getMessage());
        }
    }

    //  加载项目
    public void loadData() throws SQLException {
        List<Program> programs = (List<Program>)SqliteOpenHelper.getProgramDao().queryForAll();
        model.clear();
        for(Program program : programs) {
            model.addElement(program);
        }
        this.listProgram.setModel(model);
        if(model.isEmpty()) {
            this.menuSwitch.setEnabled(false);
            this.menuEdit.setEnabled(false);
            this.menuDelete.setEnabled(false);
        }else {
            this.menuSwitch.setEnabled(true);
            this.menuEdit.setEnabled(true);
            this.menuDelete.setEnabled(true);
        }
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        listProgram = new javax.swing.JList();
        jMenuBar1 = new javax.swing.JMenuBar();
        menuSwitch = new javax.swing.JMenu();
        menuCreate = new javax.swing.JMenu();
        menuEdit = new javax.swing.JMenu();
        menuDelete = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("项目");
        setResizable(false);

        listProgram.setModel(model);
        jScrollPane1.setViewportView(listProgram);

        menuSwitch.setText("选择");
        menuSwitch.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                menuSwitchMouseClicked(evt);
            }
        });
        jMenuBar1.add(menuSwitch);

        menuCreate.setText("新建");
        menuCreate.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                menuCreateMousePressed(evt);
            }
        });
        jMenuBar1.add(menuCreate);

        menuEdit.setText("编辑");
        menuEdit.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                menuEditMouseClicked(evt);
            }
        });
        jMenuBar1.add(menuEdit);

        menuDelete.setText("删除");
        menuDelete.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                menuDeleteMouseClicked(evt);
            }
        });
        jMenuBar1.add(menuDelete);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //  创建项目
    private void menuCreateMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuCreateMousePressed
        EditProgramDialog dialog = new EditProgramDialog((JFrame)this.getParent(),true,null,this);
        dialog.setVisible(true);
    }//GEN-LAST:event_menuCreateMousePressed

    private void menuDeleteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuDeleteMouseClicked
        if(model.isEmpty()) {
            return;
        }
        int index = ProgramDialog.this.listProgram.getLeadSelectionIndex();
        if(index < 0) {
            JOptionPane.showMessageDialog(this, "请选择项目");
        }
        int ret = JOptionPane.showConfirmDialog(null, "项目删除后将无法恢复，确定删除？", "警告", JOptionPane.YES_NO_OPTION);
        if(ret == JOptionPane.YES_OPTION) {
            Program program = (Program)model.getElementAt(index);
            try {
                ForeignCollection<Entity> entitys = program.getEntitys();
                
                List<Integer> ids = new ArrayList<Integer>();
                for(Entity entity : entitys) {
                    ForeignCollection<Field> fields = entity.getFields();
                    for(Field field : fields) {
                        ids.add(field.getId());
                    }
                }
                SqliteOpenHelper.getFieldDao().deleteIds(ids);
                SqliteOpenHelper.getEntityDao().delete(entitys);
                SqliteOpenHelper.getProgramDao().delete(program);
            }catch(Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "项目删除失败:" + e.getMessage());
            }
            model.removeElement(program);
            try {
                loadData();
            }catch(Exception e) {
                JOptionPane.showMessageDialog(this, "加载项目信息失败:" + e.getMessage());
            }
            MainFrame mainFrame = (MainFrame)this.getParent();
            if(mainFrame.getProgramId() == program.getId()) {
                mainFrame.clear();
            }
        }
    }//GEN-LAST:event_menuDeleteMouseClicked

    private void menuEditMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuEditMouseClicked
        if(model.isEmpty()) {
            return;
        }
        int index = ProgramDialog.this.listProgram.getLeadSelectionIndex();
        if(index < 0) {
            JOptionPane.showMessageDialog(this, "请选择项目");
        }
        Program program = (Program)model.getElementAt(index);
        EditProgramDialog dialog = new EditProgramDialog((JFrame)this.getParent(),true,program.getId(),this);
        dialog.setVisible(true);
    }//GEN-LAST:event_menuEditMouseClicked

    private void menuSwitchMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuSwitchMouseClicked
        if(model.isEmpty()) {
            return;
        }
        int index = ProgramDialog.this.listProgram.getLeadSelectionIndex();
        if(index < 0) {
            JOptionPane.showMessageDialog(this, "请选择项目");
            return;
        }
        Program program = (Program)model.getElementAt(index);
        MainFrame mainFrame = (MainFrame) this.getParent();
        mainFrame.design(program);
        this.dispose();
    }//GEN-LAST:event_menuSwitchMouseClicked
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList listProgram;
    private javax.swing.JMenu menuCreate;
    private javax.swing.JMenu menuDelete;
    private javax.swing.JMenu menuEdit;
    private javax.swing.JMenu menuSwitch;
    // End of variables declaration//GEN-END:variables
}
